package com.fengye.algorithms.leecode;

import com.fengye.algorithms.leecode.common.TreeNode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * @Author fengye
 * @Date 2023/4/17 4:39
 **/
public class BinaryTreeLevelOrderTraversal102 {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> result = new ArrayList<>();
        if(root == null) {
            return new ArrayList<>();
        }

        LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
        TreeNode current = null;
        //将根节点入队
        queue.offer(root);
        while(!queue.isEmpty()) {
            List<Integer> level = new ArrayList<>();
            int size = queue.size();
            // 通过for 进行层次遍历
            for(int i = 0; i < size;i++) {
                //出队队头元素并访问
                current = queue.poll();
                level.add(current.val);
                //如果当前节点的左节点不为空入队
                if (current.left != null) {
                    queue.offer(current.left);
                }
                //如果当前节点的右节点不为空，把右节点入队
                if (current.right != null) {
                    queue.offer(current.right);
                }
            }
            result.add(level);
        }
        return result;
    }
}
